package com.kevin.j2eeToolBox.xmlAnalyze.betwixt;

import java.beans.IntrospectionException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;

import com.kevin.j2eeToolBox.xmlAnalyze.Employee;
import com.kevin.j2eeToolBox.xmlAnalyze.XMLDocument;

public class BetwixtDemo implements XMLDocument {

	@Override
	public void createXml(String fileName) {

		FileWriter outputWriter = null;
		try {
			// 创建一个输出流，将用来输出Java转换的XML文件
			outputWriter = new FileWriter(fileName);
			// 输出XML的文件头
			outputWriter.write("<?xml version='1.0' ?>");
			// 创建一个BeanWriter实例，并将BeanWriter的输出重定向到指定的输出流
			BeanWriter beanWriter = new BeanWriter(outputWriter);

			// 配置BeanWriter对象
			beanWriter.getXMLIntrospector().getConfiguration()
					.setAttributesForPrimitives(false);
			beanWriter.getBindingConfiguration().setMapIDs(false);
			beanWriter.enablePrettyPrint();

			Employee employee = new Employee();
			employee.setAge(25);
			employee.setName("Test");
			employee.setSex("man");

			beanWriter.write(employee);
			// 关闭输出流
			outputWriter.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void parserXml(String fileName) {

		File file = new File(fileName);
		BeanReader reader = new BeanReader();
		Employee employee;

		try {

			reader.registerBeanClass(Employee.class);
			employee = (Employee) reader.parse(file);
			System.out.println(employee.getName());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

	}

}
